package com.innovate.nms.view;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;

import com.google.common.eventbus.Subscribe;
import com.innovate.nms.NmsApplication;
import com.innovate.nms.service.channel.Channel;
import com.innovate.nms.service.inspect.InspectScheduler;
import com.innovate.nms.service.inspect.InspectTask;
import com.innovate.nms.service.inspect.InspectTasks;
import com.ivan.toolkit.common.Debug;
import com.ivan.toolkit.common.Events;
import com.ivan.toolkit.swing.Images;

public class MonitorPanel extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2488847623385429177L;
	
	Timer timer = null;
	
	private JLabel lblStatus;
	
	private static ImageIcon wired = Images.loadResource("/images/network.png", 16, 16).getIcon();
	private static ImageIcon wireless = Images.loadResource("/images/wireless.png", 16, 16).getIcon();
	private StatusLabel lblWireless;
	private StatusLabel lblWired;
	private JList<InspectTask> list;
	private JTextArea textArea;

	/**
	 * Create the panel.
	 */
	public MonitorPanel() {
		setBorder(new EmptyBorder(0, 2, 2, 2));
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{0, 0};
		gridBagLayout.rowHeights = new int[]{0, 0, 0, 0};
		gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, 1.0, 0.0, Double.MIN_VALUE};
		setLayout(gridBagLayout);
		
		InspectGraphicPanel inspectorGraphicPanel = new InspectGraphicPanel();
		inspectorGraphicPanel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount() == 2) {
					ConfigAppDialog dlg = new ConfigAppDialog();
					dlg.start(MonitorPanel.this);
				}
				
			}
		});
		GridBagConstraints gbc_inspectorGraphicPanel = new GridBagConstraints();
		gbc_inspectorGraphicPanel.insets = new Insets(0, 0, 5, 0);
		gbc_inspectorGraphicPanel.fill = GridBagConstraints.BOTH;
		gbc_inspectorGraphicPanel.gridx = 0;
		gbc_inspectorGraphicPanel.gridy = 0;
		add(inspectorGraphicPanel, gbc_inspectorGraphicPanel);
		
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		GridBagConstraints gbc_tabbedPane = new GridBagConstraints();
		gbc_tabbedPane.insets = new Insets(0, 0, 5, 0);
		gbc_tabbedPane.fill = GridBagConstraints.BOTH;
		gbc_tabbedPane.gridx = 0;
		gbc_tabbedPane.gridy = 1;
		add(tabbedPane, gbc_tabbedPane);
		
		JScrollPane scrollPane = new JScrollPane();
		tabbedPane.addTab("监测任务", null, scrollPane, null);
		
		list = new JList<InspectTask>();
		list.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount() == 2) {
					int selected = list.getSelectedIndex();
					InspectTasks.me.inspect(selected);
				}
			}
		});
		list.setFixedCellHeight(60);
		scrollPane.setViewportView(list);
		list.setModel(InspectTasks.me);
		list.setCellRenderer(new InspectTaskPanel());
		
		InspectTaskPanel inspectTaskPanel = new InspectTaskPanel();
		scrollPane.setColumnHeaderView(inspectTaskPanel);
		
		HistoryPanel historyPanel = new HistoryPanel();
		tabbedPane.addTab("检测结果", null, historyPanel, null);
		
		JScrollPane scrollPane_1 = new JScrollPane();
		tabbedPane.addTab("检测信息", null, scrollPane_1, null);
		
		textArea = new JTextArea();
		textArea.setEditable(false);
		textArea.setFont(new Font("微软雅黑", Font.PLAIN, 18));
		scrollPane_1.setViewportView(textArea);
		
		JPanel panel = new JPanel();
		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.fill = GridBagConstraints.BOTH;
		gbc_panel.gridx = 0;
		gbc_panel.gridy = 2;
		add(panel, gbc_panel);
		
		lblStatus = new JLabel(" ");
		lblStatus.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount() == 2){
					InspectScheduler s = NmsApplication.getSpring().getBean(InspectScheduler.class);
					s.setForceOnce(true);
				}
			}
		});
		panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
		lblStatus.setForeground(new Color(0, 0, 0));
		lblStatus.setFont(new Font("微软雅黑", Font.PLAIN, 18));
		panel.add(lblStatus);
		
		Component horizontalGlue = Box.createHorizontalGlue();
		panel.add(horizontalGlue);
		
		lblWired = new StatusLabel("有线");
		lblWired.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount() == 2) {
					WiredConfigDialog dlg = new WiredConfigDialog();
					dlg.start(MonitorPanel.this);
				}
			}
		});
		lblWired.setText("有线通道");
		lblWired.setFont(new Font("微软雅黑", Font.PLAIN, 18));
		panel.add(lblWired);
		lblWired.setImage(wired, new ImageIcon(Images.gray(wired.getImage())));
		
		Component horizontalStrut = Box.createHorizontalStrut(10);
		panel.add(horizontalStrut);
		
		lblWireless = new StatusLabel("无线");
		lblWireless.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount() == 2) {
					WirelessConfigDialog dlg = new WirelessConfigDialog();
					dlg.start(MonitorPanel.this);
				}
			}
		});
		lblWireless.setText("无线通道");
		lblWireless.setFont(new Font("微软雅黑", Font.PLAIN, 18));
		panel.add(lblWireless);
		lblWireless.setImage(wireless, new ImageIcon(Images.gray(wireless.getImage())));
		
		Component horizontalStrut_1 = Box.createHorizontalStrut(10);
		panel.add(horizontalStrut_1);
		
		
		initialTimer();
		
		Events.register(this);

	}
	
	@Subscribe
	public void dipatchEvent(Events event) {
		
		if(Debug.match(event)) {
			
			long time = Debug.time(event);
			
			String source = Debug.source(event);
			
			String content = Debug.content(event);
			
			output(String.format("%s | %s | %s", dateFormat.format(time), source, content));
			
		}
		
	}
	
	public void output(String text) {
		if(textArea != null) {
			textArea.append(text + "\r\n");
			textArea.setCaretPosition(textArea.getText().length());
		}
	}
	
	private void initialTimer() {
		
		timer = new Timer(1000, new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				
				timerHandle();
				
			}
			
		});
		
		timer.start();
	}
	
	private void timerHandle() {
		
		try {
			
			updateChannelStatus();
			
			InspectScheduler task = NmsApplication.getSpring().getBean(InspectScheduler.class);
			
			long left = task.millisecondsToNext();
			
			if(left < 0) {
				
				lblStatus.setText("Scheduling now.");
				
			} else {
			
				lblStatus.setText(String.format("Next schedule left %d seconds.", left / 1000));
			
			}
			
			task.getLastTime();
		
		} catch(Exception e){}
		
	}
	
	private void updateChannelStatus() {
		
		Channel channel = Channel.getChannel("UDP");
		
		this.lblWired.setStatus(channel != null && channel.isReady());

		channel = Channel.getChannel("SMS");
		
		this.lblWireless.setStatus(channel != null && channel.isReady());
		
	}

	public static final SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
}
